package org.xinghai.sql.dialogue.controller;


import com.alibaba.dashscope.common.Role;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import org.xinghai.sql.common.api.Result;
import org.xinghai.sql.dialogue.dto.DeepSeekDto;
import org.xinghai.sql.dialogue.generator.domain.ChatHistory;
import org.xinghai.sql.dialogue.generator.service.ChatHistoryService;
import org.xinghai.sql.dialogue.service.DeepSeekService;
import org.xinghai.sql.dialogue.utils.QueryUtils;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/api")
public class DeepSeekController {
    @Autowired
    private DeepSeekService deepSeekService;
    @Autowired
    private ChatHistoryService chatHistoryService;

    /**
     * 流对话
     * @param deepSeekDto
     * @return
     */
    @PostMapping("/deepseek")
    public ResponseBodyEmitter streamDialogueResponse(@RequestBody DeepSeekDto deepSeekDto) {


        // 记录对话
        ChatHistory chatHistory = new ChatHistory();
        chatHistory.setConvId(deepSeekDto.getConvId());
        chatHistory.setRole(Role.USER.getValue());
        chatHistory.setContent(deepSeekDto.getQuery());
        chatHistoryService.save(chatHistory);

        StringBuilder sb = new StringBuilder();
        ResponseBodyEmitter emitter = new ResponseBodyEmitter();
        CompletableFuture.runAsync(() -> {
            try {
                //调用之前在数据库中查询对话id对应的对话
                List<ChatHistory> chatHistories = chatHistoryService.listByConvId(deepSeekDto.getConvId());
                //生成历史对话信息
                String query = QueryUtils.createQuery(chatHistories);
                deepSeekService.getDeepSeekResponse(deepSeekDto, emitter,sb,query);
                emitter.complete();
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        });
        emitter.onCompletion(() -> {
            // 对话结束，记录AI回复
            ChatHistory aiChatHistory = new ChatHistory();
            aiChatHistory.setConvId(deepSeekDto.getConvId());
            aiChatHistory.setRole(Role.ASSISTANT.getValue());
            aiChatHistory.setContent(String.valueOf(sb));
            chatHistoryService.save(aiChatHistory);
        });
        return emitter;
    }

    /**
     * 非流对话
     * @param deepSeekDto
     * @return
     */
    @PostMapping("/deepseek/notstream")
    public Result<String> notStreamDialogueResponse(@RequestBody DeepSeekDto deepSeekDto) {
        // 记录对话
        ChatHistory chatHistory = new ChatHistory();
        chatHistory.setConvId(deepSeekDto.getConvId());
        chatHistory.setRole(Role.USER.getValue());
        chatHistory.setContent(deepSeekDto.getQuery());
        chatHistoryService.save(chatHistory);

        StringBuilder sb = new StringBuilder();
        ResponseBodyEmitter emitter = new ResponseBodyEmitter();
                //调用之前在数据库中查询对话id对应的对话
                List<ChatHistory> chatHistories = chatHistoryService.listByConvId(deepSeekDto.getConvId());
                //生成历史对话信息
                String query = QueryUtils.createQuery(chatHistories);
                String response = deepSeekService.getDeepSeekResponseNotStream(deepSeekDto, emitter,sb,query);
            // 对话结束，记录AI回复
            ChatHistory aiChatHistory = new ChatHistory();
            aiChatHistory.setConvId(deepSeekDto.getConvId());
            aiChatHistory.setRole(Role.ASSISTANT.getValue());
            aiChatHistory.setContent(response);
            chatHistoryService.save(aiChatHistory);
            return Result.success(response);
    }

    /**
     * 清除对话数据库中的所有记录
     * @return
     */
    @DeleteMapping("/deepseek/clear")
    public Result<String> clearDialogue() {
        chatHistoryService.remove(new LambdaQueryWrapper<ChatHistory>());
        return Result.success("对话已清除");
    }

}